import { computed } from 'vue';
import useStorage from '@/composables/useStorage.ts';

const useSearchHistory = () => {

  const searchHistoryStorage = useStorage('search-history', []);

  const add = (val: string) => {
    searchHistoryStorage.setValue([...new Set([val, ...searchHistoryStorage.value.value])]);
  };

  const remove = (val?: string) => {
    if (val) {
      searchHistoryStorage.setValue(searchHistoryStorage.value.value.filter((item) => item !== val));
    } else {
      clear();
    }
  };

  const clear = () => {
    searchHistoryStorage.setValue()
  };

  const list = computed(() => searchHistoryStorage.value.value.slice(0, 6));

  return { list, add, remove, clear };
};

export default useSearchHistory;